package com.iscc.maoke.controller;

import com.google.gson.Gson;
import jdk.internal.util.xml.impl.Input;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Encoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@WebServlet("/get_net_info.do")
public class OtherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String something = request.getParameter("thing");
        String str = " http://api.avatardata.cn/ZhouGongJieMeng/LookUp?key=abc3a3bf166a419bbdbf8597f09c89f0&keyword=" + URLEncoder.encode(something, "UTF-8");
        //创建url对象
        URL url = new URL(str);
        //获取一个连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //默认get请求

        InputStream is = conn.getInputStream();

        StringBuffer buffer = new StringBuffer();
        /*String len;
        while ((len = reader.readLine()) != null) {
            buffer.append(new String(len.getBytes("iso-8859-1"), "utf-8"));
        }*/
        byte[] b = new byte[1020 * 8];
        int len;
        while ((len = is.read(b)) != -1) {
            buffer.append(new String(b, 0, len, "utf-8"));
        }
        System.out.println("buffer = " + buffer);


        is.close();

        response.getWriter().print(new Gson().toJson(buffer.toString()));

    }
}
